import React, { useEffect, useState } from 'react'
import { CircleMarker, Circle, usePlugins, useAmap } from '@amap/amap-react'
import './index.less'
import { AimOutlined, LoadingOutlined } from '@ant-design/icons'

export const GeoLocation = (props: any) => {
    const [loading, setLoading] = useState(false)
    const [position, setPosition] = useState<number[] | null>(null)
    const [radius, setRadius] = useState(-1)
    const map = useAmap()
    const ready: any = usePlugins('AMap.Geolocation')

    useEffect(() => {
        if (map && ready) {
            handleClick()
        }
    }, [map, ready])

    const callBack = (status: any, result: any) => {
        console.log(status, result)
        const { autoMove = false, onSuccess, onFail } = props
        if (map && status === 'complete') {
            setPosition([result.position.getLng(), result.position.getLat()])
            setRadius(result.accuracy)
            onSuccess && onSuccess(result)
            if (autoMove) {
                map.setCenter(result.position)
                map.setZoom(16)
            }
        }
        setLoading(false)
        onFail && onFail(result)
    }

    const handleClick = () => {
        setLoading(true)
        const geo = new ready.Geolocation({ zoomToAccuracy: true, position: 'RB' })
        geo.getCurrentPosition(callBack as any)
    }

    return (
        <>
            <div
                className='geo-location'
                onClick={() => {
                    !loading && handleClick()
                }}>
                {loading ? (
                    <LoadingOutlined style={{ fontSize: 20, color: '#fff' }} />
                ) : (
                    <AimOutlined style={{ fontSize: 20, color: '#fff' }} />
                )}
            </div>
            {position && radius > 0 && (
                <Circle
                    {...{
                        center: position,
                        radius,
                        fillOpacity: 0.1,
                        fillColor: '#344fcb',
                        strokeColor: '#344fcb',
                    }}
                />
            )}
            {position && (
                <CircleMarker
                    {...{
                        center: position,
                        radius: 7,
                        fillColor: '#344fcb',
                        fillOpacity: 1,
                        strokeColor: '#fff',
                        strokeWeight: 3,
                    }}
                />
            )}
        </>
    )
}
